using Microsoft.Extensions.Options;
using Volo.Abp.Caching;
using Volo.Abp.DependencyInjection;
using Volo.Abp.MultiTenancy;

namespace Shared.Caching.FreeRedis;

/// <summary>
/// 自定义分布式缓存键规范化器
/// 用于格式化缓存键，确保缓存键的唯一性和一致性
/// </summary>
[Dependency(ReplaceServices = true)]
public class DistributedCacheKeyNormalizer : IDistributedCacheKeyNormalizer, ITransientDependency
{
    /// <summary>
    /// 当前租户信息
    /// </summary>
    protected ICurrentTenant CurrentTenant { get; }

    /// <summary>
    /// 分布式缓存选项
    /// </summary>
    public AbpDistributedCacheOptions DistributedCacheOptions { get; }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="currentTenant">当前租户服务</param>
    /// <param name="distributedCacheOptions">分布式缓存选项</param>
    public DistributedCacheKeyNormalizer(
        ICurrentTenant currentTenant,
        IOptions<AbpDistributedCacheOptions> distributedCacheOptions)
    {
        CurrentTenant = currentTenant;
        DistributedCacheOptions = distributedCacheOptions.Value;
    }

    /// <summary>
    /// 规范化缓存键
    /// </summary>
    /// <param name="args">缓存键规范化参数</param>
    /// <returns>规范化后的缓存键</returns>
    public virtual string NormalizeKey(DistributedCacheKeyNormalizeArgs args)
    {
        // 添加全局键前缀
        var normalizedKey = $"{DistributedCacheOptions.KeyPrefix}{args.Key}";

        // 多租户缓存键处理已被注释掉
        // 如果需要多租户支持，可以取消下面的注释
        //if (!args.IgnoreMultiTenancy && CurrentTenant.Id.HasValue)
        //{
        //    normalizedKey = $"t:{CurrentTenant.Id.Value},{normalizedKey}";
        //}
        return normalizedKey;
    }
}